COMP3141
Software System Design and Implementation (18s1)

Code Example (Week 5)

module Week4 where


data Tree a
  = Leaf
  | Node a (Tree a) (Tree a)
  deriving (Show)



-- For Tree to become an instance of Functor, we have to define fmap:
--
instance Functor Tree where 

  fmap f Leaf = Leaf
  fmap f (Node x t1 t2) 
    = Node (f x) (fmap f t1) (fmap f t2)


-- a function which has the same type as fmap, but 
-- violates the functor rule
-- fmap id  = id
fakeMap :: (a ->b) -> [a] -> [b]
fakeMap f [] = undefined
fakeMap f (x : xs) = undefined

-- def of the Applicative operator <*> on the Maybe type
fappM :: Maybe (a -> b) -> Maybe a -> Maybe b
fappM  Nothing _ = Nothing
fappM  _    Nothing = Nothing
fappM (Just f) (Just x) = Just ( f x) 


-- and on the list type
fappL :: [a -> b] -> [a] -> [b]
fappL [] xs = []
fappL _  [] = []
fappL (f : fs) xs
   = map f xs ++ fappL fs xs

{- proof that the def. doesn't violate
  pure id <*> xs = xs

  fapp (pure id) xs === xs
  fapp [id] xs  == 
  map id xs ++ fapp [] xs ==
  xs  ++ []  == xs 
-}



addMaybe1 
  :: Num a => Maybe a -> Maybe a -> Maybe a
addMaybe1 (Just x) (Just y) = Just (x+y)



-- works on any monad:
addM1 mx my =
  mx    >>= \x -> 
  my    >>= \y -> 
  return (x + y)



addM2 mx my = do 
  { x <- mx
  ; y <- my 
  ; return (x + y)
  }

2018-06-14 Thu 18:28

Announcements RSS